using System;
using UnityEngine;
using UnityEngine.Audio;
using WolfCarol.AvgToolkit.Config;
using WolfCarol.AvgToolkit.Save;

namespace WolfCarol.AvgToolkit.Examples
{
    public class StageConfigData : ConfigData
    {
        public float MusicVolume;

        public float SfxVolume;

        public float VoiceVolume;

        public StageConfigData() : base()
        {
            MusicVolume = 1f;
            SfxVolume = 1f;
            VoiceVolume = 1f;
        }
    }

    public class StageConfigManager : ConfigManager, ISavable<StageConfigData>
    {
        public AudioMixer audioMixer;

        private float m_musicVolume;

        private float m_SfxVolume;

        private float m_voiceVolume;

        private void Start()
        {
            Clear();
        }

        public void SetMusicVolume(float value)
        {
            m_musicVolume = value;
            SetVolume("Music Volume", value);
        }

        public void SetSfxVolume(float value)
        {
            m_SfxVolume = value;
            SetVolume("Sfx Volume", value);
        }

        public void SetVoiceVolume(float value)
        {
            m_voiceVolume = value;
            SetVolume("Voice Volume", value);
        }

        private void SetVolume(string name, float value)
        {
            if (audioMixer == null)
            {
                throw new NullReferenceException("AudioMixer was empty.");
            }

            float v = 1f - value;
            audioMixer.SetFloat(name, -60f * v * v * v * v);
        }

        public void Clear()
        {
            SetWindowMode(FullScreenMode.FullScreenWindow);
            SetResolution(1920, 1080);
            SetFrameRate(60);
            SetMusicVolume(1f);
            SetSfxVolume(1f);
            SetSfxVolume(1f);
        }

        public StageConfigData Save()
        {
            return new StageConfigData()
            {
                WindowMode = Screen.fullScreenMode,
                ScreenWidth = Screen.width,
                ScreenHeight = Screen.height,
                FrameRate = Application.targetFrameRate,
                MusicVolume = m_musicVolume,
                SfxVolume = m_SfxVolume,
                VoiceVolume = m_voiceVolume
            };
        }

        public void Load(StageConfigData obj)
        {
            SetWindowMode(obj.WindowMode);
            SetResolution(obj.ScreenWidth, obj.ScreenHeight);
            SetFrameRate(obj.FrameRate);
            m_musicVolume = obj.MusicVolume;
            SetMusicVolume(m_musicVolume);
            m_SfxVolume = obj.SfxVolume;
            SetSfxVolume(m_SfxVolume);
            m_voiceVolume = obj.VoiceVolume;
            SetVoiceVolume(m_voiceVolume);
        }
    }
}
